<template>
  <div>
    <MainContent title="机构管理">
      <template #search-bar>
        <SearchBar inline>
          <template #normal>
            <el-form-item>
              <el-input v-model="params.name" placeholder="机构名称" clearable>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="params.status" placeholder="机构状态" clearable>
                <el-option label="启用" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </template>
          <template #toolbar>
            <el-form-item>
              <el-button type="primary" @click="getManagePageList">查询</el-button>

              <!-- TODO 加权限 -->
              <el-button type="primary" @click="showExportData = true">导出</el-button>
            </el-form-item>
          </template>
        </SearchBar>
      </template>

      <el-table :data="state.tableData" row-key="id" stripe default-expand-all v-loading="state.isLoading">
        <el-table-column prop="name" label="机构名称" min-width="180" />
        <el-table-column prop="empCount" label="员工数量" min-width="100" />
        <el-table-column prop="insNo" label="机构号" min-width="100" />
        <el-table-column prop="description" label="机构描述" show-overflow-tooltip min-width="160" />
        <el-table-column prop="updateTime" label="更新时间" min-width="160">
          <template #default="scope">
            {{ new Date(scope.row.updateTime).format("yyyy-MM-dd hh:mm") }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" class="ml-2" :active-value="1" :inactive-value="0" inline-prompt
              active-text="启用" inactive-text="禁用" disabled />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="280">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="editManageForm(scope.row)"
              v-has="['1011']">编辑</el-button>
            <el-button type="primary" size="small" link v-if="scope.row.status"
              @click="updateManageStatus(scope.row.id, 0, scope.row.name)" v-has="['1012']">停用</el-button>
            <el-button type="primary" size="small" link v-else
              @click="updateManageStatus(scope.row.id, 1, scope.row.name)" v-has="['1012']">启用
            </el-button>
            <el-dropdown @command="handleCommand($event, scope.row)" placement="top">
              <div style="margin-left: 10px; cursor: pointer">
                <el-button type="primary" link size="small" v-has="['1013', '1014']">更多</el-button>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="addChildren" v-has="['1013']">新增子机构</el-dropdown-item>
                  <el-dropdown-item command="toStaff" v-has="['1014']">员工列表</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </MainContent>
    <el-dialog class="dialog-form" v-model="dialogFormVisible" :title="title" width="30%" :before-close="resetForm"
      :close-on-click-modal="false">
      <el-form :model="form" ref="manageForm" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="机构名称" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="机构号" prop="机构号">
          <el-input v-model="form.insNo" autocomplete="off" placeholder="机构号" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="机构描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述信息" autocomplete="off" maxlength="200"
            show-word-limit />
        </el-form-item>
        <el-form-item label="应用权限" prop="serviceList">
          <el-checkbox-group v-model="form.serviceList">
            <el-checkbox v-for=" item  in  appList " :label="item.code" :disabled="!serviceList.includes(item.code)"
              name="type">{{ item.name }}</el-checkbox>
            <!-- <el-checkbox label="MERCHANT" :disabled="!serviceList.includes('MERCHANT')" name="type">商户系统</el-checkbox>
            <el-checkbox label="ACTIVITY" :disabled="!serviceList.includes('ACTIVITY')" name="type">营销活动管理</el-checkbox>
            <el-checkbox label="FLOW" :disabled="!serviceList.includes('FLOW')" name="type">营销自动化</el-checkbox>
            <el-checkbox label="MALL" :disabled="!serviceList.includes('MALL')" name="type">商城管理</el-checkbox>
            <el-checkbox label="MATERIAL" :disabled="!serviceList.includes('MATERIAL')" name="type">内容管理</el-checkbox>
            <el-checkbox label="MARKETING" :disabled="!serviceList.includes('MARKETING')" name="type">员工营销工具
            </el-checkbox>
            <el-checkbox label="AD" :disabled="!serviceList.includes('AD')" name="type">智能广告</el-checkbox> -->
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(manageForm, edit)">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog class="children-form" v-model="dialogChildrenVisible" title="新增子机构" width="30%"
      :before-close="resetChildrenForm" :close-on-click-modal="false">
      <el-form :model="childrenForm" ref="childrenEditForm" :rules="rules" label-width="95px">
        <el-form-item label="上级机构" prop="name">
          <el-input v-model="childrenForm.parentName" autocomplete="off" placeholder="机构名称" maxlength="30"
            show-word-limit disabled />
        </el-form-item>
        <el-form-item label="子机构名称" prop="name">
          <el-input v-model="childrenForm.name" autocomplete="off" maxlength="30" show-word-limit placeholder="子机构名称" />
        </el-form-item>
        <el-form-item label="机构号" prop="insNo">
          <el-input v-model="childrenForm.insNo" autocomplete="off" placeholder="机构号" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="机构描述">
          <el-input v-model="childrenForm.description" type="textarea" placeholder="请输入描述信息" autocomplete="off"
            maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="应用权限" prop="serviceList">
          <el-checkbox-group v-model="childrenForm.serviceList">
            <el-checkbox v-for=" item  in  appList " :label="item.code" :disabled="!serviceList.includes(item.code)"
              name="type">{{ item.name }}</el-checkbox>
            <!-- <el-checkbox label="MERCHANT" :disabled="!serviceList.includes('MERCHANT')" name="type">商户系统</el-checkbox>
            <el-checkbox label="ACTIVITY" :disabled="!serviceList.includes('ACTIVITY')" name="type">营销活动管理</el-checkbox>
            <el-checkbox label="FLOW" :disabled="!serviceList.includes('FLOW')" name="type">营销自动化</el-checkbox>
            <el-checkbox label="MALL" :disabled="!serviceList.includes('MALL')" name="type">商城管理</el-checkbox>
            <el-checkbox label="MATERIAL" :disabled="!serviceList.includes('MATERIAL')" name="type">内容管理</el-checkbox>
            <el-checkbox label="MARKETING" :disabled="!serviceList.includes('MARKETING')" name="type">员工营销工具
            </el-checkbox>
            <el-checkbox label="AD" :disabled="!serviceList.includes('AD')" name="type">智能广告</el-checkbox> -->
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetChildrenForm()">取消</el-button>
          <el-button type="primary" @click="submitChildrenForm(childrenEditForm)">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <exportData v-model:show-dialog="showExportData" :search-data="params" title="机构管理" export-type="insExport">
    </exportData>
  </div>
</template>
<script lang="ts">
export default {
  name: 'OrganizationManage'
}
</script>
<script lang="ts" setup>
import exportData from "@/components/exportData/exportData.vue";
import { reactive, onMounted } from "vue";
import {
  queryTree,
  addNew,
  update,
  upStatus,
  serviceByParent,
} from "@/api/orgManage";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { manageReq, manageUpdate } from "@/api/modules/orgManage";
import { queryAppList } from "@/api/orgPosition";
import { debounceUtils } from "@/utils/index.js";
// filterTemplate,
const router = useRouter();
const showExportData = ref(false)
const state = reactive({
  id: "",
  isLoading: false,
  total: 0,
  tableData: [] as Array<manageReq>,
});
const params = ref({
  name: "",
  status: "",
});
let serviceList = ref([] as Array<String>);
let form = ref({
  parentId: "",
  id: "",
  name: "",
  //组件标识
  insNo: "",
  //描述
  description: "",
  // 应用权限
  serviceList: [] as Array<any>,
});
let childrenForm = ref({
  parentId: "",
  parentName: "",
  name: "",
  //组件标识
  insNo: "",
  //描述
  description: "",
  // 应用权限
  serviceList: [] as Array<any>,
});
let statusTitle = ref("停用");
const manageForm = ref<FormInstance>();
const childrenEditForm = ref<FormInstance>();
let edit = ref(false);
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入机构名称",
      trigger: "blur",
    },
  ],
  serviceList: [
    {
      required: true,
      message: "请选择应用权限",
      trigger: "blur",
    },
  ],
});
const dialogFormVisible = ref(false);
const dialogChildrenVisible = ref(false);

let title = ref("新增机构");

const addManage = () => {
  title.value = "新建机构";
  edit.value = false;
  getParentServiceList("");
  dialogFormVisible.value = true;
};
const appList = ref([] as Array<any>);
const getAppPageList = async (): Promise<void> => {
  const rs = await queryAppList({
    simple: true,
    includeMerchant: true,
  });
  if (rs.code == 200) {
    appList.value = rs.payload;
  }
};
const toStaff = (id: number) => {
  router.push("/merchant/organization/manage/staff/" + id);
};
const addChildren = (id: string | number, name: string) => {
  Object.assign(childrenForm.value, {
    ...{
      parentId: id,
      parentName: name,
    },
  });
  getParentServiceList(id);
  dialogChildrenVisible.value = true;
};
const getManagePageList = debounceUtils(async (): Promise<void> => {
  state.isLoading = true;
  const rs = await queryTree(params.value);
  if (rs.code == 200) {
    state.tableData = rs.payload;
  }
  state.isLoading = false;
}, 500);

const editManageForm = async (val: manageUpdate): Promise<void> => {
  Object.assign(form.value, {
    ...val,
  });
  title.value = "编辑机构";
  edit.value = true;
  getParentServiceList(val.parentId);
  dialogFormVisible.value = true;
};
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let rs;
      if (edit) {
        delete form.value.children;
        rs = await update(form.value);
      } else {
        rs = await addNew(form.value);
      }
      if (rs.code == 200) {
        resetForm();
        getManagePageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const submitChildrenForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const rs = await addNew(childrenForm.value);
      if (rs.code == 200) {
        ElMessage({
          message: "新增子机构成功",
          type: "success",
        });
        resetChildrenForm();
        getManagePageList();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = () => {
  form.value = {
    parentId: "",
    id: "",
    name: "",
    insNo: "",
    //描述
    description: "",
    // 超管账号
    serviceList: [] as Array<any>,
  };
  manageForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const resetChildrenForm = () => {
  childrenForm.value = {
    parentId: "",
    parentName: "",
    name: "",
    //组件标识
    insNo: "",
    //描述
    description: "",
    // 应用权限
    serviceList: [] as Array<any>,
  };
  childrenEditForm.value?.resetFields();
  dialogChildrenVisible.value = false;
};
const updateManageStatus = async (
  id: string | number,
  status: string | number,
  name: string
) => {
  ElMessageBox.confirm(status ? "确定启用吗" : "确定停用吗", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await upStatus({
        id: id,
        status: status,
        name: name
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: status ? "启用成功" : "停用成功",
        });
        getManagePageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getParentServiceList = async (id: string | number) => {
  const rs = await serviceByParent({
    parentId: id,
  });
  if (rs.code == 200) {
    serviceList.value = rs.payload.serviceList;
  }
};
watch(params.value, (val) => {
  getManagePageList();
});
const handleCommand = (command: string, row: any) => {
  if (command === "addChildren") {
    addChildren(row.id, row.name)
  } else if (command === "toStaff") {
    toStaff(row.id)
  }
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getAppPageList();
    getManagePageList();
  },
  {
    deep: true
  }
)

onMounted(() => {
  getAppPageList();
  getManagePageList();

});
</script>
<style lang="scss" scoped>
//:deep(.el-form) {
//  text-align: left;
//  margin-top: 18px;
//}
// .btn-func {
//   .el-button + .el-button {
//     margin-left: 0;
//   }

// }
:deep(.el-button--text) {
  margin: 0 !important;
}

:deep(.el-button--small) {
  padding: 5px;
}

:deep(.el-table) {
  margin: 0 auto;
}

.page {
  margin: 10px auto;
}

.dialog-form {
  :deep(.el-date-editor) {
    width: 100%;
  }
}
</style>
